#include "socket.h"

TCP_CLient_Socket::TCP_CLient_Socket()
{
    server_con();
}

TCP_CLient_Socket::~TCP_CLient_Socket()
{
    close(sockfd);
}

bool TCP_CLient_Socket::server_con()
{
    int ret = 0;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        std::cout << "Error creating socket" << std::endl;
        exit(-1);
    }

    ret = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret == -1)
    {
        std::cout << "Error connecting to server" << std::endl;
        exit(-1);
    }
    return true;
}

void TCP_CLient_Socket::send_message(std::string data)
{
    send(sockfd, data.c_str(), data.length(), 0);
}

void TCP_CLient_Socket::rece_message()
{
    char buffer[1024];
    memset(buffer, 0, 1024);
    int len = recv(sockfd, buffer, 1024, 0);
    if (len == -1)
    {
        std::cout << "Error receiving data" << std::endl;
        exit(-1);
    }
    else if (len == 0)
    {
        cout << "Server closed the connection" << endl;
        return;
    }
    std::cout << buffer << std::endl;
    // std::string data(buffer);
    // return data;
}